package com.zxy.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.common.annotation.AutoFill;
import com.zxy.common.constant.StatusConstant;
import com.zxy.common.context.BaseContext;
import com.zxy.common.enumeration.OperationType;
import com.zxy.common.result.PageResult;
import com.zxy.common.result.Result;
import com.zxy.mapper.ActivityMapper;
import com.zxy.mapper.OpportunityMapper;


import com.zxy.mapper.SysUserMapper;
import com.zxy.pojo.dto.BusinessQueryDTO;
import com.zxy.pojo.dto.ContractDTO;
import com.zxy.pojo.dto.UpdateCustomerDTO;
import com.zxy.pojo.entity.*;
import com.zxy.pojo.vo.CustomerDetailVO;
import com.zxy.service.ContractService;
import com.zxy.service.OpportunityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class OpportunityServiceImpl extends ServiceImpl<OpportunityMapper, CustomerClue> implements OpportunityService {
    @Autowired
    private OpportunityMapper opportunityMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ContractService contractService;

    /**
     * 查询商机列表
     *
     * @param query
     * @return
     */

    @Override
    public PageResult listByPage(BusinessQueryDTO query) {
        // 计算偏移量
        int offset = (query.getPageNum() - 1) * query.getPageSize();
        query.setPageNum(offset); // 复用 pageNum 作为 LIMIT 的 offset


        List<CustomerClue> list = opportunityMapper.selectBusinessList(query);
        Long total = opportunityMapper.countBusinessList(query);

        return new PageResult(total, list);
    }


    /**
     * 新增商机
     *
     * @param customerClue
     * @return
     */
    @Override
    @AutoFill(value = OperationType.INSERT)
    public boolean saves(CustomerClue customerClue) {
        //默认状态为 1
        customerClue.setStatus(String.valueOf(StatusConstant.ENABLE));
        return save(customerClue);
    }


    /**
     * 查询商机跟进记录
     *
     * @param businessId
     * @return
     */
    @Override
    public List<BusinessRecord> getListByBusinessId(Long businessId) {
        List<BusinessRecord> records = opportunityMapper.selectByBusinessId(businessId);


        for (BusinessRecord record : records) {
            // 将 keyItems 按逗号拆分，转为 List<String>
            if (record.getKeyItems() != null && !record.getKeyItems().trim().isEmpty()) {
                List<String> keys = new ArrayList<>(
                        Arrays.asList(record.getKeyItems().split("\\s*,\\s*"))
                );
                record.setKeys(keys);
            } else {
                record.setKeys(new ArrayList<>());
            }
        }
        return records;
    }

    /**
     * 查询客户详情
     *
     * @param id
     * @return
     */
    @Override
    public CustomerDetailVO getByIds(Long id) {
        return opportunityMapper.getCustomerDetailById(id);
    }


    /**
     * 新增商机跟进记录
     *
     * @param record
     * @return
     */
    @Override
    @AutoFill(OperationType.INSERT)
    public boolean addRecord(BusinessRecord record) {
        LocalDateTime now = LocalDateTime.now();

        // 设置时间
        record.setCreateTime(now);
        record.setUpdateTime(now);

        // 设置操作人
        if (record.getUpdateBy() == null || record.getUpdateBy().isEmpty()) {
            Long currentId = BaseContext.getCurrentId();
            record.setUpdateBy(currentId != null ? "user" + currentId : "system");
        }
        
        // 设置创建人
        if (record.getCreateBy() == null || record.getCreateBy().isEmpty()) {
            Long currentId = BaseContext.getCurrentId();
            record.setCreateBy(currentId != null ? "user" + currentId : "system");
        }

        // ====== 关键：自动更新客户主表 ======
        if (record.getBusinessId() != null) {
            CustomerClue updateClue = new CustomerClue();
            updateClue.setId(record.getBusinessId());

            // 1. 更新下次跟进时间
            if (record.getNextTime() != null) {
                updateClue.setNextTime(record.getNextTime());
            }

            // 2. 更新最新备注（同步最新沟通内容）
            if (record.getRecord() != null && !record.getRecord().trim().isEmpty()) {
                updateClue.setRemark(record.getRecord());
            }

            // 3. 更新操作人和时间
            updateClue.setUpdateBy(record.getUpdateBy());
            updateClue.setUpdateTime(now);

            opportunityMapper.updateById(updateClue);
        }

        // 插入跟进记录
        return opportunityMapper.addRecord(record) > 0;
    }


    /**
     * 商机分配
     *
     * @param ids
     * @param userId
     * @return
     */
    @Override
    public String assignment(Long[] ids, Long userId) {
        log.info("开始分配商机，商机ID列表: {}，用户ID: {}", ids, userId);

        // 查询当前用户已分配的商机
        int count = opportunityMapper.countAssignClueByUser(userId);
        log.info("用户 {} 当前已分配商机数: {}", userId, count);

        if (count >= 3) {
            log.warn("用户 {} 已分配商机数达到上限3个", userId);
            return "当前用户已分配商机数达到上限";
        }

        // 查询分配的用户信息
        SysUser assignUser = userMapper.selectUserById(userId);
        if (assignUser == null) {
            log.error("用户ID {} 不存在", userId);
            return "分配用户不存在";
        }

        // 计算还能分配多少个商机
        int remainingSlots = 3 - count;
        log.info("用户 {} 还能分配 {} 个商机", userId, remainingSlots);

        // 遍历商机ID进行分配
        int assignedCount = 0;
        for (Long clueId : ids) {
            // 如果已达到分配上限，则停止分配
            if (assignedCount >= remainingSlots) {
                log.info("用户 {} 已达到分配上限，停止分配", userId);
                break;
            }

            // 查询商机信息
            CustomerClue clue = opportunityMapper.selectClueById(clueId);
            if (clue == null) {
                log.warn("商机ID {} 不存在，跳过分配", clueId);
                continue;
            }

            // 更新商机状态为"跟进中"(状态值为2)
            clue.setStatus("2"); // 跟进中
            clue.setUserId(userId);
            clue.setUpdateTime(LocalDateTime.now());
            clue.setOwner(assignUser.getUserName()); // 设置归属人为用户名
            opportunityMapper.updateClue(clue);

            // 添加分配记录
            ClueAssignRecord assignRecord = new ClueAssignRecord();
            assignRecord.setAssignId(clueId);
            assignRecord.setUserId(userId);
            assignRecord.setUserName(assignUser.getUserName()); // 设置用户名
            assignRecord.setCreateBy(clue.getCreateBy()); // 设置操作人
            assignRecord.setCreateTime(new Date());
            assignRecord.setLatest("1"); // 当前最新分配人
            assignRecord.setType("0"); // 正常分配
            opportunityMapper.insertAssignRecord(assignRecord);

            assignedCount++;
            log.info("商机 {} 分配给用户 {}({}) 成功", clueId, userId, assignUser.getUserName());
        }

        log.info("商机分配完成，成功分配 {} 个商机给用户 {}", assignedCount, userId);
        return "成功分配 " + assignedCount + " 个商机";
    }


    /**
     * 回退操作
     *
     * @param id   业务ID
     * @param type 操作类型
     * @return
     */
    @Override
    public boolean backOperation(Long id, Integer type) {
        // 不再判断type的具体值，直接执行踢回商机池的操作
        String otherStatus = getOtherStatusValue();
        if (otherStatus == null) {
            log.error("未能找到'其他'状态的字典值");
            return false; // 如果找不到对应的状态值，直接返回失败
        }
        return rollbackToPool(id, otherStatus);
    }

    /**
     * 获取"其他"状态的字典值
     * @return 字典值
     */
    /**
     * 获取"其他"状态的字典值
     *
     * @return 字典值
     */
    private String getOtherStatusValue() {
        // 查询reasons_for_business类型的字典，因为"其他"拒绝理由属于这个类型
        List<ActivityDict> dictList = activityMapper.selectDictListByType("reasons_for_business");

        for (ActivityDict dict : dictList) {
            // 根据字典标签查找对应的字典值
            if ("其他".equals(dict.getDictLabel())) {
                return dict.getDictValue();
            }
        }

        log.error("未能找到'其他'状态的字典值，检查字典表配置");
        return "6"; // 默认返回6，这是"其他"状态的dict_value
    }


    /**
     * 回滚到商机池
     *
     * @param id     商机ID
     * @param status 状态值
     * @return 是否成功
     */
    private boolean rollbackToPool(Long id, String status) {
        CustomerClue clue = new CustomerClue();
        clue.setId(id);
        clue.setStatus(status);
        clue.setUserId(null); // 清空归属人
        clue.setOwner(null); // 清空归属人名称
        clue.setOwnerTime(null); // 清空归属时间
        clue.setUpdateTime(LocalDateTime.now());
        return updateById(clue);
    }


    /**
     * 捞取商机
     *
     * @param businessId 商机ID
     * @return
     */
    @Override
    public Result gainBusiness(Long businessId) {
        log.info("开始捞取商机,商机id = {}", businessId);

        try {
            // 查询商机是否存在
            CustomerClue business = this.getById(businessId);
            if (business == null) {
                return Result.error("商机不存在,id = {} " + businessId);
            }


            business.setStatus("1");
            business.setUpdateTime(LocalDateTime.now());

            // 更新商机
            boolean updateResult = this.updateById(business);

            if (updateResult) {
                log.info("成功捞取商机,id = {}", businessId);
                return Result.success("捞取成功");
            } else {
                log.error("捞取商机失败,id = {}", businessId);
                return Result.error("捞取失败");
            }
        } catch (Exception e) {
            log.error("捞取商机时发生错误", e);
            return Result.error("捞取失败: " + e.getMessage());
        }
    }


    /**
     * 转换商机为合同
     *
     * @param id
     */
    @Override
    public void changeContract(Long id) {
        log.info("开始商机转合同, 商机id = {}", id);

        //检索商机是否存在
        CustomerClue business = this.getById(id);
        if (business == null) {
            log.error("商机不存在,id = {}", id);
            return;
        }

        // 验证线索状态，只有状态为"跟进中"(状态值为2)的商机才能转为合同
        if (!"2".equals(business.getStatus())) {
            log.error("当前商机不能转为合同, 当前状态: {}", business.getStatus());
            return;
        }

        // 创建ContractDTO对象并填充基本信息
        ContractDTO contractDTO = new ContractDTO();
        contractDTO.setName(business.getName());
        contractDTO.setPhone(business.getPhone());
        contractDTO.setChannel(business.getChannel());
        contractDTO.setActivityId(business.getActivityId());
        // 设置合同编号
        contractDTO.setContractNo("HT" + System.currentTimeMillis());

        // 设置关联信息
        // 注意：ContractDTO中的courseId是String类型，而CustomerClue中的courseId是Integer类型
        if (business.getCourseId() != null) {
            contractDTO.setCourseId(String.valueOf(business.getCourseId()));
        }

        // 调用合同服务创建合同记录
        contractService.addContract(contractDTO);

        // 更新商机状态为已转合同(例如状态值为3)
        business.setStatus("3");
        business.setUpdateTime(LocalDateTime.now());
        this.updateById(business);

        log.info("商机转合同完成, 商机id = {}", id);
    }







}






